new Vue({
    el: '#app',
    data() {
        return {
            form: {
                SQL_SerialNumber: '',//标识
                SQL_Name: '',//名称
                SQL_Statement: '',//sql字符串
                Line_JSON: '',//连线
                Selecte_Table: '',//选择的表
                Table_Name: '',//
                SQL_Type:'0',
            },
            rules: [],
            table: [],//全部表
            SQL_Statement:'',
            tableName: '',//主表表名
            tableData: [],//主表全部字段
            subTable: [],//关联表
            selecteTable: [],//选中表
            showTable: [],//sql预览查询
            isShow: true,
            Join: [{
                label: '左连接',
                value: 'LEFT JOIN'
            }, {
                label: '右连接',
                value: 'RIGHT JOIN'
            }, {
                label: '内连接',
                value: 'INNER JOIN'
            }],//连接方式
            jsPlumbInstance: "", //jsPlumb实例
            jsPlumbSetting: {
                // 动态锚点、位置自适应
                Anchors: ['Top', 'TopCenter', 'TopRight', 'TopLeft', 'Right', 'RightMiddle', 'Bottom', 'BottomCenter', 'BottomRight', 'BottomLeft', 'Left', 'LeftMiddle'],
                // 连线的样式 StateMachine、Flowchart，Bezier、Straight
                Connector: ['StateMachine', { curviness: 60 }],
                // 鼠标是否拖动删除线
                ConnectionsDetachable: false,
                // 删除线的时候节点不删除
                DeleteEndpointsOnDetach: false,
                // 连线的两端端点类型：矩形 Rectangle；圆形Dot； eight: 矩形的高 ，idth: 矩形的宽
                Endpoints: [['Dot', { radius: 2, }], ['Dot', { radius: 2 }]],
                // 线端点的样式
                EndpointStyle: { fill: '#67C23A', outlineWidth: 1, radius: 5 },
                // 绘制连线
                PaintStyle: {
                    stroke: '#67C23A',
                    strokeWidth: 1,
                    outlineStroke: 'transparent',
                    // 设定线外边的宽，单位px
                    outlineWidth: 10
                },
                // 绘制连线箭头
                Overlays: [// 箭头叠加
                    ['Arrow', {
                        width: 10, // 箭头尾部的宽度
                        length: 8, // 从箭头的尾部到头部的距离
                        location: 1, // 位置，建议使用0～1之间
                        direction: 1, // 方向，默认值为1（表示向前），可选-1（表示向后）
                        foldback: 0.623 // 折回，也就是尾翼的角度，默认0.623，当为1时，为正三角
                    }]
                ],
                // 绘制图的模式 svg、canvas
                RenderMode: 'svg',
                DragOptions: { cursor: 'pointer', zIndex: 2000 },
                // 鼠标滑过线的样式
                HoverPaintStyle: { stroke: '#F56C6C', strokeWidth: 1, cursor: 'pointer' },
            },
            // 连线的配置
            jsPlumbConnectOptions: {
                isSource: true,
                isTarget: true,
                // 动态锚点、提供了4个方向 Continuous、AutoDefault
                anchor: "Continuous",
                overlays: [['Arrow', { width: 8, length: 8, location: 1 }]] // overlay
            },
            commonLink: {
                isSource: true,
                isTarget: true,
                anchor: ["Perimeter", { shape: "Circle" }],
                connector: ['StateMachine'],//Bezier贝塞尔曲线，Flowchart流程图连接线， StateMachine曲线， Straight直线
                endpoint: 'Dot',//设置为点
                maxConnections: -1,// 不限制节点的连线数量,
            },
            nodeList: [],
            lineList: [],//连接线
            selectLine: {},//选中连接线
            dialogVisible: false,
            loading: false,
        }
    },
    computed: {
        allTableData() {
            return [...this.tableData, ...this.configTable(this.tableName)]
        },
        sqlString() {
            let sql = "";
            this.allTableData.filter(i => i.isShow).forEach((item, index) => {
                if (index == 0) {
                    sql = "SELECT " + item.TABLE_NAME + "." + item.COLUMN_NAME;
                } else {
                    sql = sql + ",\r\n" + item.TABLE_NAME + "." + item.COLUMN_NAME;
                }
                //判断是否有指定名称
                if (item.NickName) {
                    sql = sql + " As " + item.NickName
                }
            })
            if (sql) {
                sql = sql + "\r\nFROM " + this.tableName;
                this.lineList.forEach(item => {
                    sql = sql + "\r\n" + item.Join + " " + item.targetId + " ON " + item.sourceUuid.slice(0, -2) + " = " + item.targetUuid.slice(0, -2)
                })
            }
            return sql;
        }
    },
    watch: {
        tableName(Data) {
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryAllColumnByTableName`,
                type: 'GET',
                data: { Data },
                success: function (data) {
                    if (data.length > 0) {
                        data.forEach(item => {
                            item.NickName = '';
                            item.isShow = true;
                        })
                        that.tableData = data;
                        const timer = setTimeout(() => {
                            data.forEach((obj, index) => {
                                that.jsPlumbInstance.addEndpoint(Data, {
                                    anchor: [0, accAdd(accDiv(index + 1, data.length + 1), accDiv(1, data.length + 1) / 2), 0, 0],
                                    uuid: Data + '.' + Data.COLUMN_NAME + '-0'
                                }, that.commonLink)
                                that.jsPlumbInstance.addEndpoint(Data, {
                                    anchor: [1, accAdd(accDiv(index + 1, data.length + 1), accDiv(1, data.length + 1) / 2), 0, 0],
                                    uuid: Data + '.' + obj.COLUMN_NAME + '-1'
                                }, that.commonLink)
                            })
                            that.jsPlumbInstance.draggable(Data)
                            clearTimeout(timer);
                        })
                    }
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
        },
        selecteTable(Data) {
            const that = this;
            Data.forEach(item => {
                if (!this.subTable.some(i => i.tableName == item)) {
                    $.ajax({
                        headers: requestHeaders(),
                        url: `${BASE_URL2}/generalBusiness/generalQueryAllColumnByTableName`,
                        type: 'GET',
                        data: { Data: item },
                        success: function (data) {
                            data.forEach(item => {
                                item.NickName = '';
                                item.isShow = true;
                            })
                            that.subTable.push({
                                tableName: item,
                                top: 0,
                                left: 0,
                                tableData: data
                            });
                            const timer = setTimeout(() => {
                                // 添加锚点
                                data.forEach((obj, index) => {
                                    that.jsPlumbInstance.addEndpoint(item, {
                                        anchor: [0, accAdd(accDiv(index + 1, data.length + 1), accDiv(1, data.length + 1) / 2), 0, 0],
                                        uuid: item + '.' + obj.COLUMN_NAME + '-0'
                                    }, that.commonLink)
                                    that.jsPlumbInstance.addEndpoint(item, {
                                        anchor: [1, accAdd(accDiv(index + 1, data.length + 1), accDiv(1, data.length + 1) / 2), 0, 0],
                                        uuid: item + '.' + obj.COLUMN_NAME + '-1'
                                    }, that.commonLink)
                                })
                                // 添加拖拽
                                that.jsPlumbInstance.draggable(item);
                                // that.jsPlumbInstance.repaintEverything();
                                clearTimeout(timer);
                            })
                        },
                        complete: function (XMLHttpRequest) {
                            requestPretreatment(XMLHttpRequest);
                        },
                        dataType: "json"
                    })
                }
            })
            //筛掉取消的表
            this.subTable = this.subTable.filter(i => Data.some(tableName => tableName == i.tableName))
            that.jsPlumbInstance.repaintEverything();
        },
        sqlString(SQL) {
            const that = this;
            this.isShow = false;
            // $.ajax({
            //     url: `${BASE_URL1}/essc/SQLAction`,
            //     type: 'POST',
            //     data: { SQL },
            //     success: function (res) {
            //         if (res.Status=="success") {
            //             that.showTable = res.Data
            //         }else{
            //             that.showTable = [];
            //         }
            //         that.isShow = true;
            //     },
            //     dataType: "json"
            // })
        }
    },
    mounted() {
        this.getInfo();
        this.getData();
    },
    methods: {
        configTable(tableName) {
            let Data = []
            this.lineList.filter(i => i.sourceId == tableName).forEach(item => {
                let Data1 = this.subTable.filter(i => i.tableName == item.targetId)[0].tableData;
                let Data2 = this.configTable(item.targetId)
                Data = [...Data1, ...Data2];
            })
            return Data;
        },
        getData() {
            const that = this;
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalQueryAllTableName`,
                type: 'GET',
                success: function (res) {
                    that.table = res;
                },
                complete: function (XMLHttpRequest) {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
        },
        getInfo() {
            this.$nextTick().then(() => {
                jsPlumb.ready(() => {
                    // 创建jsPlumb实例
                    this.jsPlumbInstance = jsPlumb.getInstance();
                    // 导入准备好的jsPlumb配置
                    this.jsPlumbInstance.importDefaults(this.jsPlumbSetting);
                    //连线前监听，阻止一些不允许的连线
                    this.jsPlumbInstance.bind('beforeDrop', (event) => {
                        if (event.sourceId == event.targetId) { //当与自己表连线时，阻止连线
                            return false
                        } else if (event.targetId == this.tableName) {//被连线的是主表时，取消连线
                            this.$message({
                                message: '被连接的表不能为主表',
                                type: 'warning'
                            });
                            return false
                        } else if (event.sourceId != this.tableName && !this.lineList.some(i => i.targetId == event.sourceId)) {//若连接表不为主表，则该表需要校验连接表是否跟主表有关系才能进行连接
                            this.$message({
                                message: '当前表暂未与主表关联，无法连接其它表',
                                type: 'warning'
                            });
                            return false
                        }
                        return true // 链接会自动建立
                    })
                    // 监听连线事件
                    this.jsPlumbInstance.bind('connection', (event) => {
                        const Join = "LEFT JOIN";
                        //在连接线上添加文字
                        var labelOverlay = ["Label", {
                            label: this.Join.filter(i => i.value == Join)[0].label, // 要显示的文字  
                            location: 0.5, // 文字在连接线上的位置（0 到 1 之间的值）
                            cssClass: "connection-label",// 可选的 CSS 类名，用于自定义样式
                            id: "labelOverlay" + event.connection.id
                        }];
                        this.lineList.push({
                            sourceId: event.sourceId,
                            targetId: event.targetId,
                            sourceUuid: event.connection.endpoints[0].getUuid(),
                            targetUuid: event.connection.endpoints[1].getUuid(),
                            Join,
                            connection: event.connection
                        })
                        event.connection.addOverlay(labelOverlay);
                    });
                    // 监听删除连线事件
                    // this.jsPlumbInstance.bind('connectionDetached', (event) => {
                    //     console.log('Connection detached:', event);
                    // });
                    // 点击连接事件
                    this.jsPlumbInstance.bind('click', (connection) => {
                        let sourceUuid = connection.endpoints[0].getUuid();
                        let targetUuid = connection.endpoints[1].getUuid();
                        this.selectLine = this.lineList.filter(i => i.sourceUuid == sourceUuid && i.targetUuid == targetUuid)[0];
                        this.selectLine.Join_Original = this.selectLine.Join;
                        this.dialogVisible = true;
                        // this.jsPlumbInstance.connect({
                        //     uuids:[targetUuidId,sourceUuidId],
                        // });
                    });
                    // this.getData1();
                    // 开始节点间的连线
                    // this.lineList.forEach((item) => {
                    //     this.jsPlumbInstance.connect(item, this.jsPlumbConnectOptions);
                    // });
                    // // 让每个节点都可以被拖拽
                    // this.nodeList.forEach((item, index) => {
                    //     this.jsPlumbInstance.draggable("node-" + (index + 1),{
                    //         containment: "wrapper",
                    //     })
                    //     // 给每个节点添加锚点
                    //     this.jsPlumbInstance.addEndpoint("node-" + (index + 1), {
                    //         anchor: ['Bottom', 'Top', 'Left', 'Right'],
                    //         Overlays: [
                    //             ['Arrow', { width: 10, length: 8, location: 1, direction: 1, foldback: 0.623 }]]
                    //     }, this.commonLink)
                    // })
                    // this.jsPlumbInstance.repaintEverything(); // 重绘
                })
            })
        },
        cancel() { //取消
            this.dialogVisible = false;
            this.selectLine.Join = this.selectLine.Join_Original;
        },
        submitSave() {//保存
            if (this.selectLine.Join != this.selectLine.Join_Original) {
                console.log(this.lineList);
                this.lineList.filter(i => i.targetId == this.selectLine.targetId).forEach(item => {
                    const overlays = item.connection.getOverlays();
                    //获取文字对象
                    for (let key in overlays) {
                        if (key.startsWith("labelOverlay")) {
                            //移除旧的overlays，
                            item.connection.removeOverlays(key);
                        }
                    }
                    //添加新的
                    item.connection.addOverlay(["Label", {
                        label: this.Join.filter(i => i.value == this.selectLine.Join)[0].label, // 要显示的文字  
                        location: 0.5, // 文字在连接线上的位置（0 到 1 之间的值）
                        cssClass: "connection-label",// 可选的 CSS 类名，用于自定义样式
                        id: "labelOverlay" + item.connection.id
                    }])
                })
            }
            this.dialogVisible = false;
        },
        removeLine(targetId, sourceId) {//删除线条，递归
            if (!this.lineList.some(i => i.targetId == targetId && i.sourceId != sourceId)) {
                this.lineList.filter(i => i.sourceId == targetId).forEach(item => {
                    this.jsPlumbInstance.deleteConnection(item.connection);
                    this.removeLine(item.targetId, item.sourceId);
                })
                this.lineList = this.lineList.filter(i => i.sourceId != targetId);
            }
        },
        removeSave() {//删除
            this.$confirm('确定删除此连线吗, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const { sourceUuid, targetUuid, sourceId, targetId, connection } = this.selectLine;
                this.jsPlumbInstance.deleteConnection(connection);
                this.lineList = this.lineList.filter(i => i.sourceUuid != sourceUuid && i.targetUuid != targetUuid);
                this.removeLine(targetId, sourceId)//判断被连表有无其它被连接线条，没有删除该表发起的所以线条
                this.selectLine = {};
                this.dialogVisible = false;
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
            }).catch(() => { });
        },
        submitForm() {
            const that = this;
            let arr = []
            this.lineList.forEach(item => {
                arr.push({
                    sourceId: item.sourceId,
                    targetId: item.targetId,
                    sourceUuid: item.sourceUuid,
                    targetUuid: item.targetUuid,
                    Join: item.Join,
                });
            })
            this.form.Line_JSON = JSON.stringify(arr);
            this.form.Table_Name = this.tableName;
            this.form.Selecte_Table = JSON.stringify(this.selecteTable);
            if(this.form.SQL_Type == '0'){
                this.form.SQL_Statement = window.btoa(unescape(encodeURIComponent(this.sqlString)));
            }else{
                this.form.SQL_Statement = window.btoa(unescape(encodeURIComponent(this.SQL_Statement)));
            }
            $.ajax({
                headers: requestHeaders(),
                url: `${BASE_URL2}/generalBusiness/generalSave`,
                type: 'POST',
                data: {
                    Data: JSON.stringify({ Add: { base_sql_list: [this.form] } })
                },
                success: function (res) {
                    if (res.Status === 'success') {
                        that.$message.success("提交成功")
                        window.history.go(-1)
                    } else {
                        that.$message.error("提交失败，请稍后再试")
                    }
                },
                error: function () {
                    that.$message.error("操作失败，请稍后再试")
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false;
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json"
            })
            // this.connection.addOverlay([
            //     "Label", {
            //         label: "自定义文字", // 要显示的文字  
            //         location: 0.5, // 文字在连接线上的位置（0 到 1 之间的值）  
            //         id: 'aaa', // 可选的 Overlay ID，用于后续可能的操作  
            //         cssClass: "connection-label" // 可选的 CSS 类名，用于自定义样式  
            //     }
            // ])
        },
        getData1() {
            this.tableName = 'base_config_info';
            let arr = [{ "sourceId": "base_config_info", "targetId": "base_enterprise_info", "sourceUuid": "base_config_info.accordion-1", "targetUuid": "base_enterprise_info.Enterprise_Name-0", "Join": "LEFT JOIN" }, { "sourceId": "base_config_info", "targetId": "base_operation_log", "sourceUuid": "base_config_info.allowCustom-1", "targetUuid": "base_operation_log.Enterprise_SerialNumber-0", "Join": "LEFT JOIN" }]
            this.selecteTable = ["base_enterprise_info", "base_operation_log"];
            setTimeout(() => {
                this.jsPlumbInstance.connect({
                    uuids: ['base_config_info.accordion-1', 'base_enterprise_info.Enterprise_Name-0'],
                });
            }, 1000)
            // this.jsPlumbInstance.repaintEverything(); // 重绘
            // arr.forEach(item=>{
            //     console.log([item.sourceUuid,item.targetUuid]);
            //     this.jsPlumbInstance.connect({
            //         uuids:[item.sourceUuid,item.targetUuid],
            //     });
            // })
        },
        getData2() {

        }
    }
})